using BasicData.API.Application.Command;
using BasicData.API.Dtos;
using BasicData.Domain.Entities;
using BasicData.ErrorCode;
using BasicData.Infrastructure.Interfasce;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace BasicData.API.Application.CommandHandlers
{
    /// <summary>
    /// 获取商品命令处理器
    /// </summary>
    public class GetGoodsCommandHandler : IRequestHandler<GetGoodsCommand, APIResult<List<GoodsDTO>>>
    {
        private readonly IBaseRepositroy<Goods> _goodsRepository;
        private readonly ILogger<GetGoodsCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="goodsRepository">商品仓储</param>
        /// <param name="logger">日志</param>
        public GetGoodsCommandHandler(IBaseRepositroy<Goods> goodsRepository, ILogger<GetGoodsCommandHandler> logger)
        {
            _goodsRepository = goodsRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理获取商品命令
        /// </summary>
        /// <param name="request">命令</param>
        /// <param name="cancellationToken">取消标记</param>
        /// <returns>商品列表</returns>
        public async Task<APIResult<List<GoodsDTO>>> Handle(GetGoodsCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始获取所有商品列表");

                // 查询所有商品，不添加任何条件
                var goods = await _goodsRepository.GetAllAsync().ToListAsync(cancellationToken);

                // 转换为DTO，只使用实体中存在的字段
                var goodsDTOs = goods.Select(g => new GoodsDTO
                {
                    GoodsId = g.GoodsId,
                    GoodsName = g.GoodsName
                }).ToList();

                _logger.LogInformation("成功获取商品列表，共 {Count} 条记录", goodsDTOs.Count);

                return new APIResult<List<GoodsDTO>>
                {
                    Code = ResultCode.查询成功,
                    Message = "获取商品列表成功",
                    Data = goodsDTOs
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取商品列表时发生错误");
                return new APIResult<List<GoodsDTO>>
                {
                    Code = ResultCode.查询失败,
                    Message = $"获取商品列表失败: {ex.Message}"
                };
            }
        }
    }
} 